﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Windows.Controls.Primitives;
//Internal Reference Below
using ProtoImaginer.ProtoProject;
using ProtoImaginer.Models;

namespace ProtoImaginer
{
    public partial class MainPage : PhoneApplicationPage
    {
        public static IList<Project> MyProjects = new List<Project>();
        public static string guid = "null";
        //[Meng Huasong] I have changed this to true for demo used
        protected static Boolean SignedIn = true;

        // Constructor
        public MainPage()
        {
            CreateDatabase();

            MyProjects = FetchAllRecords();
            InitializeComponent();
            checkSign();
            checkProject();
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel Items
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            App.ViewModel.LoadData();
            Refresh();
        }
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        #region RefreshFunction&Timer

        protected void Refresh()
        {
            MyProjects = FetchAllRecords();
            App.ViewModel.LoadData();
            //Customized Codes Here
            checkSign();
            checkProject();
        }
        void OnTimerTick(object sender, EventArgs e)
        {
            UpdateClock();
        }

        void UpdateClock()
        {
            Refresh();
        }

        protected void checkProject()
        {
            if(MainViewModel.projectListEmpty)
            {
                ProjectListBox.Visibility = Visibility.Collapsed;
                NoProjectNotice.Visibility = Visibility.Visible;
            }
            else
            {
                ProjectListBox.Visibility = Visibility.Visible;
                NoProjectNotice.Visibility = Visibility.Collapsed;
            }
        }

        private void checkSign()
        {
            if (!SignedIn)
            {
                SignInText.Visibility = Visibility.Visible;
                SignUpButton.Visibility = Visibility.Visible;
                SignInButton.Visibility = Visibility.Visible;
                ShareIcon.Visibility = Visibility.Collapsed;
                ShareText.Visibility = Visibility.Collapsed;
                CheckSubmIcon.Visibility = Visibility.Collapsed;
                CheckSubmText.Visibility = Visibility.Collapsed;
                ProfileIcon.Visibility = Visibility.Collapsed;
                ViewProfileText.Visibility = Visibility.Collapsed;
                SignOutText.Visibility = Visibility.Collapsed;
            }
            else
            {
                ShareIcon.Visibility = Visibility.Visible;
                ShareText.Visibility = Visibility.Visible;
                CheckSubmIcon.Visibility = Visibility.Visible;
                CheckSubmText.Visibility = Visibility.Visible;
                ProfileIcon.Visibility = Visibility.Visible;
                ViewProfileText.Visibility = Visibility.Visible;
                SignOutText.Visibility = Visibility.Visible;
                SignInText.Visibility = Visibility.Collapsed;
                SignUpButton.Visibility = Visibility.Collapsed;
                SignInButton.Visibility = Visibility.Collapsed;
            }
        }

        #endregion

        #region DatabaseQueryFunction

        private const string strConnectionString = @"isostore:/protoDataContext.sdf";
        public static Models.Image tempImg;
        public static void CreateDatabase()
        {
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                if (database.DatabaseExists() == false)
                {
                    database.CreateDatabase();
                    //MessageBox.Show("Database Created Successfully!!!");
                    InsertFakeData();
                }
                //else { MessageBox.Show("Database already exists!!!"); }
            }

            using (Models.ProtoDataContext pageDB = new Models.ProtoDataContext("isostore:/protoDataContext.sdf"))
            {
                IQueryable<Models.Image> images = from a in pageDB.Images
                                                  where a.ImageThumb.Contains("00.jpg")
                                                  select a;
                tempImg = images.FirstOrDefault();
            }
            tempImg.ImageSource = "/ProtoImaginer;component/Images/PageFullSize/00.jpg";
            Models.ProtoDataContext.SaveImage(tempImg);
        }
        private static void InsertFakeData()
        {
            Random rd = new Random();

            //new Project(String projectTitlte, String projectTag, String projectThumb);
            Project project0 = new Project("Campus Bus Guide", "ntu,bus,guide,campus", "00.jpg");
            Project project1 = new Project("Alarm", "ntu,school,student,alarm,time", "10.jpg");
            Project project2 = new Project("Smartphone Guide", "phone,guide,shopping,purchase,mobile", "20.jpg");
            Project project3 = new Project("Flashlight", "utility,flash,light,flashlight", "30.jpg");
            Project project4 = new Project("Student Portal", "productivity,student,class,course,ntu,student,portal", "40.jpg");
            Project project5 = new Project("Converter", "converter,currency,unit,utility", "50.jpg");


            Models.Page page00 = new Models.Page(project0.ProjectId, "home page");
            Models.Page page01 = new Models.Page(project0.ProjectId, "bus page");
            Models.Page page02 = new Models.Page(project0.ProjectId, "stop page");

            Models.Page page10 = new Models.Page(project1.ProjectId, "home page");
            Models.Page page11 = new Models.Page(project1.ProjectId, "new alarm");

            Models.Page page20 = new Models.Page(project2.ProjectId, "home page");
            Models.Page page21 = new Models.Page(project2.ProjectId, "choose OS");
            Models.Page page22 = new Models.Page(project2.ProjectId, "result");

            Models.Page page30 = new Models.Page(project3.ProjectId, "home page");
            Models.Page page31 = new Models.Page(project3.ProjectId, "customize");

            Models.Page page40 = new Models.Page(project4.ProjectId, "portal page");
            Models.Page page41 = new Models.Page(project4.ProjectId, "portfolio");
            Models.Page page42 = new Models.Page(project4.ProjectId, "course");
            Models.Page page43 = new Models.Page(project4.ProjectId, "notification");
            Models.Page page44 = new Models.Page(project4.ProjectId, "schedule");

            Models.Page page50 = new Models.Page(project5.ProjectId, "converter");
            Models.Page page51 = new Models.Page(project5.ProjectId, "category");

            //new Models.Image(Stirng pageId, String imageSource, String imageThumb);
            Models.Image image00 = new Models.Image(page00.PageId, "00.jpg", "00.jpg");
            Models.Image image01 = new Models.Image(page01.PageId, "01.jpg", "01.jpg");
            Models.Image image02 = new Models.Image(page02.PageId, "02.jpg", "02.jpg");

            Models.Image image10 = new Models.Image(page10.PageId, "10.jpg", "10.jpg");
            Models.Image image11 = new Models.Image(page11.PageId, "11.jpg", "11.jpg");

            Models.Image image20 = new Models.Image(page20.PageId, "20.jpg", "20.jpg");
            Models.Image image21 = new Models.Image(page21.PageId, "21.jpg", "21.jpg");
            Models.Image image22 = new Models.Image(page22.PageId, "22.jpg", "22.jpg");

            Models.Image image30 = new Models.Image(page30.PageId, "30.jpg", "30.jpg");
            Models.Image image31 = new Models.Image(page31.PageId, "31.jpg", "31.jpg");

            Models.Image image40 = new Models.Image(page40.PageId, "40.jpg", "40.jpg");
            Models.Image image41 = new Models.Image(page41.PageId, "41.jpg", "41.jpg");
            Models.Image image42 = new Models.Image(page42.PageId, "42.jpg", "42.jpg");
            Models.Image image43 = new Models.Image(page43.PageId, "43.jpg", "43.jpg");
            Models.Image image44 = new Models.Image(page44.PageId, "44.jpg", "44.jpg");

            Models.Image image50 = new Models.Image(page50.PageId, "50.jpg", "50.jpg");
            Models.Image image51 = new Models.Image(page51.PageId, "51.jpg", "51.jpg");

            Models.ProtoDataContext.AddProject(project0);
            Models.ProtoDataContext.AddProject(project1);
            Models.ProtoDataContext.AddProject(project2);
            Models.ProtoDataContext.AddProject(project3);
            Models.ProtoDataContext.AddProject(project4);
            Models.ProtoDataContext.AddProject(project5);

            Models.ProtoDataContext.AddPage(page00);
            Models.ProtoDataContext.AddPage(page01);
            Models.ProtoDataContext.AddPage(page02);

            Models.ProtoDataContext.AddPage(page10);
            Models.ProtoDataContext.AddPage(page11);
            
            Models.ProtoDataContext.AddPage(page20);
            Models.ProtoDataContext.AddPage(page21);
            Models.ProtoDataContext.AddPage(page22);
            
            Models.ProtoDataContext.AddPage(page30);
            Models.ProtoDataContext.AddPage(page31);
            
            Models.ProtoDataContext.AddPage(page40);
            Models.ProtoDataContext.AddPage(page41);
            Models.ProtoDataContext.AddPage(page42);
            Models.ProtoDataContext.AddPage(page43);
            Models.ProtoDataContext.AddPage(page44);
            
            Models.ProtoDataContext.AddPage(page50);
            Models.ProtoDataContext.AddPage(page51);

            Models.ProtoDataContext.AddImage(image00);
            Models.ProtoDataContext.AddImage(image01);
            Models.ProtoDataContext.AddImage(image02);

            Models.ProtoDataContext.AddImage(image10);
            Models.ProtoDataContext.AddImage(image11);

            Models.ProtoDataContext.AddImage(image20);
            Models.ProtoDataContext.AddImage(image21);
            Models.ProtoDataContext.AddImage(image22);

            Models.ProtoDataContext.AddImage(image30);
            Models.ProtoDataContext.AddImage(image31);

            Models.ProtoDataContext.AddImage(image40);
            Models.ProtoDataContext.AddImage(image41);
            Models.ProtoDataContext.AddImage(image42);
            Models.ProtoDataContext.AddImage(image43);
            Models.ProtoDataContext.AddImage(image44);

            Models.ProtoDataContext.AddImage(image50);
            Models.ProtoDataContext.AddImage(image51);
        }

        public static void AddNewRecord(Project p)
        {
            if (p.ProjectName.Length == 0)
            {
                MessageBox.Show("null!");
                return;
            }
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                Project newProject = new Project(
                    p.ProjectId,
                    p.ProjectAuthor,
                    p.ProjectName,
                    p.ProjectStatus,
                    p.ProjectDescription,
                    p.ProjectTag,
                    p.ProjectCreateDate,
                    p.ProjectLastModifiedDate,
                    p.ProjectThumb
                    );
                database.Projects.InsertOnSubmit(newProject);
                try
                {
                    database.SubmitChanges();
                }
                catch (Exception e1)
                {
                    Console.WriteLine(e1);
                    database.SubmitChanges();
                }
                //MessageBox.Show("Employee Added Successfully!!!");
            }
        }

        public static IList<Project> FetchAllRecords()
        {
            //IList<Project> RecordList = new List<Project>();
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                IQueryable<Project> query
                    = from pjt in database.Projects
                      orderby pjt.ProjectLastModifiedDate descending
                      //orderby pjt.Field<DateTime>("ProjectLastModifiedDate")
                      select pjt;
                return query.ToList();
            }
        }
        
        public static Project QueryProjectRecordById(string id) 
        {
            
            IList<Project> RecordList = null;
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                IQueryable<Project> query = from pjt in database.Projects where pjt.ProjectId == id.ToString() select pjt;
                RecordList = query.ToList();
            }
            return RecordList[0];
        }

        public static void ListAllProjectRecords()
        {
            IList<Project> PjtList = null;
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                IQueryable<Project> query = from pjt in database.Projects select pjt;
                PjtList = query.ToList();
            }
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.AppendLine("Project List");
            foreach (Project pt in PjtList)
            {
                strBuilder.AppendLine("Name - " + pt.ProjectName + " Created On - " + pt.ProjectCreateDate.ToString());
            }
            MessageBox.Show(strBuilder.ToString());
        }

        //NOT WORK
        public static void UpdateRecords(Project p)
        {
            if (p.ProjectName.Length == 0)
            {
                MessageBox.Show("null!");
                return;
            }
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                p.ProjectLastModifiedDate = DateTime.Now;
                Models.ProtoDataContext.SaveProject(p);
                Models.ProtoDataContext.AddProject(p);
                //IQueryable<Project> record = from pjt in database.Projects where pjt.ProjectId == p.ProjectId select pjt;
                //Project projectToUpdate = record.FirstOrDefault();
                //projectToUpdate.ProjectLastModifiedDate = DateTime.Now;
                //projectToUpdate.ProjectDescription = p.ProjectDescription;
                //projectToUpdate.ProjectName = p.ProjectName;
                //projectToUpdate.ProjectTag = p.ProjectTag;
                //database.SubmitChanges();
                //IQueryable<Project> recor = from pjt in database.Projects where pjt.ProjectId == p.ProjectId select pjt;
                //Project projectToUpdat = recor.FirstOrDefault();
                //MessageBox.Show(projectToUpdat.ProjectName);
            }
        }

        public static void DeleteRecord(Project p)
        {
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                IQueryable<Project> query = from pjt in database.Projects where pjt.ProjectId == p.ProjectId select pjt;
                Project PjtToRemove = query.FirstOrDefault();
                database.Projects.DeleteOnSubmit(PjtToRemove);
                database.SubmitChanges();
                //MessageBox.Show("Project Deleted Successfully!!!");
            }
        }

        public static void DeleteDatabase()
        {
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                if (database.DatabaseExists())
                {
                    database.DeleteDatabase();
                    MessageBox.Show("Database Deleted Successfully!!!");
                }
            }
        }
        #endregion

        #region Page1_Projects_Functions&Members

        private void NewButton_Click(object sender, RoutedEventArgs e)
        {
            Popup popup = new Popup();
            popup.VerticalOffset = 0;
            ProtoProject.NewProjectPopup control = new ProtoProject.NewProjectPopup();
            popup.Child = control;
            popup.IsOpen = true;
            control.OK_Button.Click += (s, args) =>
            {
                popup.IsOpen = false;
                Guid guid;
                // Create and display the value of two GUIDs.
                guid = Guid.NewGuid();
                Project temp = new Project(control.NewProjectName_TextBox.Text, "null", "-1.jpg");
                //MainPage.AddNewRecord(temp);
                ProtoImaginer.Models.ProtoDataContext.AddProject(temp);
                Refresh();
            };
            control.Cancel_Button.Click += (s, args) =>
            {
                popup.IsOpen = false;
            };
        }

        private void Remove_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            ListBoxItem selectedListBoxItem = this.ProjectListBox.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
            ItemViewModel itemToDelete = selectedListBoxItem.DataContext as ItemViewModel;
            DeleteSelected(MyProjects.ToList(), itemToDelete.ItemID);
            Refresh();
        }

        public void DeleteSelected(List<Project> list, string id)
        {
            foreach (Project p in list)
            {
                if (p.ProjectId == id)
                {
                    DeleteRecord(p);
                }
            }
        }

        // Handle selection changed on ListBox
        private void ProjectListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If selected index is -1 (no selection) do nothing
            if (ProjectListBox.SelectedIndex == -1)
                return;
            NavigationService.Navigate(new Uri("/ProtoProject/ViewProject.xaml?selectedItem=" + ProjectListBox.SelectedIndex, UriKind.Relative));
            ProjectListBox.SelectedIndex = -1;
        }

        private void SearchProject_Click(object sender, RoutedEventArgs e)
        {
            //NavigationService.Navigate(new Uri("/ProtoPage/PageView.xaml?name=", UriKind.Relative));
            NavigationService.Navigate(new Uri("/ProtoProject/SearchByName.xaml", UriKind.Relative));
        }
        #endregion

        #region Page2_Community_Functions&Members
        private void SignInPressed(object sender, RoutedEventArgs e)
        {
            SignedIn = true;
            //Refresh the view
            Refresh();
        }
        private void SignOutAction(object sender, RoutedEventArgs e)
        {
            SignedIn = false;
            //Refresh the view
            Refresh();
        }

        private void View_Profile_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/ProtoCommunity/ViewProfile.xaml", UriKind.Relative));
        }

        private void Check_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/ProtoCommunity/CheckProject.xaml", UriKind.Relative));
        }

        private void Share_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/ProtoCommunity/ShareProject.xaml", UriKind.Relative));
        }
        #endregion

        #region Page3_TopProjects_Functions&Members
        private void SearchBox_Focus(object sender, RoutedEventArgs e)
        {
            searchTag_Text.SelectAll();
            //Here is the code to show result
        }

        private void MouseLeftButtonUp_SearchTag(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/ProtoProject/SearchByTag.xaml?tag=" + searchTag_Text.Text, UriKind.Relative));
        }
        #endregion

        #region Page4_About/Help_Functions&Members
        private void about_click(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Miscellaneous/AboutPage.xaml", UriKind.Relative));
        }

        private void help_click(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Miscellaneous/HelpPage.xaml", UriKind.Relative));
        }

        private void donate_click(object sender, MouseButtonEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Send email to us?", "Donate to MetaMind", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                EmailComposeTask emailComposeTask = new EmailComposeTask();
                emailComposeTask.Subject = "I Want to Donate";
                emailComposeTask.To = "metamind@gmail.com";
                emailComposeTask.Show();
            }
        }

        private void contact_us_click(object sender, MouseButtonEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Send email to us?", "Contact Us", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                EmailComposeTask emailComposeTask = new EmailComposeTask();
                emailComposeTask.To = "metamind@gmail.com";
                emailComposeTask.Show();
            }
        }
        #endregion

        private void MenuItemQuit_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("Menu item 1 works!");
            throw new Exception();
        }



    }
}